<?php

namespace App\Http\Requests;

use App\Models\ProductSku;

class OrderRequest extends Request
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            // 微信授权地址必须 json格式传入
            'address'           => ['required','json'],
            'freight_price'     => ['required','numeric'],
            'total_amount'      => ['required','numeric'],
            'items'             => [
                'required',
                'json',
                function($attribute, $value, $fail) {
                    $data = json_decode($value, true);
                    foreach ($data as $v) {
                        if (!isset($v['sku_id'])) {
                            return $fail('规格不能为空');
                        }
                        if (!$sku = ProductSku::find($v['sku_id'])) {
                            return $fail('该商品不存在');
                        }
                        if (!$sku->product->on_sale) {
                            return $fail('该商品未上架');
                        }
                        if ($sku->product->seckill()->begin()->first()) {
                            return $fail('该商品属于秒杀商品，不支持该下单方式');
                        }
                        if ($sku->stock === 0) {
                            return $fail('该商品已售完');
                        }
                        // 根据索引找到用户所提交的购买数量
                        if(!isset($v['amount']))
                        {
                            return $fail('商品数量不能为空');
                        }
                        if ($v['amount'] > 0 && $v['amount'] > $sku->stock) {
                            return $fail('该商品库存不足');
                        }
                    }
                }
            ],
            'form_id'           => ['required'],
        ];
    }

    public function messages()
    {
        return [
            'items.required' => '请设置商品数据',
            'items.*.sku_id.required' => '请设置商品sku',
            'items.*.amount.min' => '商品下单数量最少为1',
        ];
    }
}
